package org.seed.quantum.socket;

import java.nio.channels.CompletionHandler;

class ReadCompletionHandler implements CompletionHandler<Integer, SocketSession> {

    /**
     * 处理消息读回调事件
     *
     * @param result  已读消息字节数
     * @param session 当前触发读回调的会话
     */
    @Override
    public void completed(final Integer result, final SocketSession session) {
        try {
            // 接收到的消息进行预处理
            NetMonitor monitor = session.getServerConfig().getMonitor();
            if (monitor != null) {
                monitor.afterRead(session, result);
            }
            //触发读回调
            session.flipRead(result == -1);
            session.signalRead();
        } catch (Exception e) {
            failed(e, session);
        }
    }


    @Override
    public final void failed(Throwable exc, SocketSession session) {
        try {
            session.getServerConfig().getProcessor().stateEvent(session, SocketStateEnum.INPUT_EXCEPTION, exc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            session.close(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
